package dao;/*
 * H2parent
 * dao
 * @author wuqiang@kedacom.com
 * @date 2019/1/30
 */

import model.Person;
import utils.H2JdbcUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class PersonDaoImpl implements PersonDao {

    /**
     * 增加
     * @param person
     */
    @Override
    public void add(Person person) {
        Connection connection = H2JdbcUtil.getConnection();
        Statement statement=null;
        try{
            statement=connection.createStatement();
            StringBuilder sb=new StringBuilder("insert into person(name,age) ");
            sb.append(" values('"+person.getName()+"','"+person.getAge()+"')");
            statement.execute(sb.toString());
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            H2JdbcUtil.close(connection,statement);
        }
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<Person> getAll() {
        Connection connection = H2JdbcUtil.getConnection();
        Statement statement=null;
        ResultSet rs=null;
        List<Person> data=new ArrayList<Person>();
        try{
            statement=connection.createStatement();
            StringBuilder sb=new StringBuilder("select t.id,t.name,t.age from person t ");
            rs = statement.executeQuery(sb.toString());
            while(rs.next()){
                Person person=new Person();
                int id = rs.getInt("id");
                person.setId(id);
                String name = rs.getString("name");
                person.setName(name);
                int age = rs.getInt("age");
                person.setAge(age);
                data.add(person);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            H2JdbcUtil.close(connection,statement,rs);
        }
        return data;
    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
    @Override
    public Person findById(Integer id) {
        return null;
    }

    /**
     * 根据姓名查询
     *
     * @param name
     * @return
     */
    @Override
    public Person findByName(String name) {
        return null;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {

    }

    /**
     * 更新
     *
     * @param person
     */
    @Override
    public void update(Person person) {

    }
}
